package day_7_17;

import java.util.Deque;
import java.util.LinkedList;

public class Main1 {
    /**
     * 173. 二叉搜索树迭代器
     * https://leetcode.cn/problems/binary-search-tree-iterator/description/?envType=study-plan-v2&envId=top-interview-150
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class BSTIterator {
        // 就是在做中序遍历
        private TreeNode cur;
        private Deque<TreeNode> stack;

        public BSTIterator(TreeNode root) {
            cur = root;
            stack = new LinkedList<>();
        }

        public int next() {
            // 往左侧遍历，并进行记录
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 这时候遍历到最后，将最后一个记录的数据拿出，就是第一个值
            cur = stack.pop();
            int ret = cur.val;
            // 之后往右侧进行遍历
            cur = cur.right;
            return ret;
        }

        public boolean hasNext() {
            return cur != null || !stack.isEmpty();
        }
    }
}
